﻿using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace DenisVuyka.Controls.PropertyGrid.Metadata
{
  public class AttributesContainer
  {
    private AttributeCollection attributes;
    private Dictionary<string, Type> keys = new Dictionary<string, Type>();
    public const string AttributeSuffix = "Attribute";

    public AttributesContainer(AttributeCollection attributes)
    {
      this.attributes = attributes;

      foreach (Attribute attr in attributes)
      {
        Type type = attr.GetType();
        RegisterAttribute(type.Name, type);
      }
    }

    private bool RegisterAttribute(string name, Type attributeType)
    {
      string attributeName = name.EndsWith(AttributeSuffix)
        ? name.Remove(name.Length - AttributeSuffix.Length, AttributeSuffix.Length)
        : name;

      if (!keys.ContainsKey(attributeName))
      {
        keys.Add(attributeName, attributeType);
        return true;
      }
      return false;
    }

    public object this[string key]
    {
      get
      {
        if (this.attributes != null)
        {
          Type type = null;
          if (keys.TryGetValue(key, out type))
            return this.attributes[type];
        }
        return null;
      }
    }
  }
}
